import random
from flask import Flask, Response
from Utils.RedisHelper import RedisHelper
import json

app = Flask(__name__)

@app.route('/',methods=['GET','POST'])
def home():
    return '<h1>Home</h1>'


@app.route('/get', methods=['GET','POST'])
def get():
    redis = RedisHelper()
    keys = redis.getkeys()
    key = random.choice(keys)
    data = redis.get(key)
    proxy = '{0}:{1}'.format(data['ip'], data['port'])
    return proxy


@app.route('/getall',methods=['GET','POST'])
def getall():
    redis = RedisHelper()
    list = redis.getall()
    dic = []
    for item in list:
        dic.append(eval(item))
    jsondata = json.dumps(dic)
    return Response(json.dumps(dic), mimetype='application/json')


@app.route('/gettxt',methods=['GET','POST'])
def gettxt():
    redis = RedisHelper()
    all = redis.getall()
    txt = ''
    for item in all:
        item = eval(item)
        proxy = '{0}:{1}'.format(item['ip'], item['port'])
        txt = txt + proxy+'<br />'
    return txt


@app.route('/gettemp', methods=['GET', 'POST'])
def gettemp():
    redis = RedisHelper()
    keys = redis.temp_getkeys()
    dic = []
    for key in keys:
        data = redis.temp_get(key)
        dic.append(data)
    return Response(json.dumps(dic), mimetype='application/json')



def runapi():
    app.run(port=8010)

if __name__ == '__main__':
    app.run(debug=True,port=8010)